<template>
  <div class="work-order-list">
    <!-- <div class="work-order-list-top"> -->
    <CommonHeader title="采购入库新增" :is-show-back="true" class="header-top" />
    <addForm ref="addForm"></addForm>
    <!-- 内容区域 -->
    <CommonMain>
      <template>
        <van-pull-refresh v-model="refreshing" :disabled="isRefreshDisable" @refresh="onRefresh">
          <van-list v-if="infoList.length > 0" :finished="finished" finished-text="没有更多了"
            @load="onLoad" :immediate-check="false">
            <MateriaItem v-for="(item, index) in infoList" :key="index" :index="index" :infoData="infoData"
              :single-material="item" :tabState="searchParams.dataState" @updateMaterialRemark="updateMaterialRemark"
              @updateMaterialExpand="updateMaterialExpand" :showCheckBox="false">
              <template slot="action">
                <!-- <el-button @click="printDialog(item)">打印 </el-button> -->
                <!-- <el-button @click="printDialog(item)">删除批次 </el-button> -->
              </template>
            </MateriaItem>
          </van-list>
        </van-pull-refresh>
      </template>
    </CommonMain>
    <img src="@/assets/images/allocation/scan.png" class="scan-img" v-draggable @click="scanChange" />
    <footer class="action">
      <section @click="showBottomMore = !showBottomMore" class="more" v-show="false">
        <img src="@/assets/images/more.png" alt="" />
        <span>更多</span>
        <section v-show="showBottomMore" class="popover">
          <el-button type="text" @click.stop="allSelect"
            v-if="searchParams.dataState == 3 && !this.allChecked">全选</el-button>
          <el-button type="text" @click.stop="allSelectcanel"
            v-if="searchParams.dataState == 3 && this.allChecked">取消全选</el-button>
          <el-button type="text" @click.stop="allSelectdataState"
            v-if="searchParams.dataState != 3 && !this.allCheckedSelect">全选</el-button>
          <el-button type="text" @click.stop="allSelectcaneldataState"
            v-if="searchParams.dataState != 3 && this.allCheckedSelect">取消全选</el-button>
          <el-button type="text" @click.stop="allExpandOrFold">
            {{ isAllExpand ? "全部收起" : "全部展开" }}
          </el-button>
          <!-- <el-button type="text"
                style="color:#F82A2A"
                @click.stop="handleDelete"
                >删除</el-button
            > -->
        </section>
      </section>
      <el-button type="primary" class="btn" style="width: 100%" @click="confirmWarehousing" :loading="btnLoading"
      loading-text="正在提交...">提交</el-button>
      <!-- <el-button type="primary" class="btn" @click="handleAddSelectInfoList"
        v-if="searchParams.dataState == 1 && infoData.state != 2">确认已选({{ SlectedLength }}/{{ materSlectedLength
        }})</el-button> -->
    </footer>
    <!-- dialog -->
    <!-- <sku-dialog :visible.sync="skuVsibel"></sku-dialog> -->
    <!--  -->
    <van-dialog v-model="showRealNum" title="实际数量" show-cancel-button confirm-button-color="#548AF1"
      @confirm="realNumHandleConfirm" @cancel="realNumHandleCancel">
      <van-form ref="realNumForm" @submit.native.prevent>
        <van-field ref="realNumInput" name="realNum" v-model="realNum" type="number" label="实际数量" :rules="getRealNum()"
          @focus="selectAllTextReal" />
      </van-form>
    </van-dialog>
    <van-dialog v-model="planAmountshow" title="计划数量" show-cancel-button confirm-button-color="#548AF1"
      :before-close="beforClose" @confirm="numHandleConfirm" @cancel="numHandleCancel">
      <van-form ref="planAmountForm" @submit.native.prevent>
        <van-field ref="planNumInput" name="planAmount" v-model="planAmount" type="number" label="计划数量"
          :rules="getPlanAmount()" @focus="selectAllTextPlan" />
      </van-form>
    </van-dialog>
    <van-popup v-model="showPicker" style="width: 100%" position="bottom">
      <van-picker title="批次品质" show-toolbar :columns="mqList" @confirm="onConfirm" @cancel="onCancel" value-key="label"
        style="width: 100%" />
    </van-popup>
    <!--物料特征参数选择弹窗 -->
    <ChoiceSpecificParamsDialog v-if="choiceSpecificParamstVisible" :show="choiceSpecificParamstVisible"
      :material-code="skuData.stockInventoryDetailEntity.materialFields.code"
      :sku-id="skuData.stockInventoryDetailEntity.skuId" @confirm="confirmChoiceSpecificParams"
      @cancel="cancelChoiceSpecificParams" />
    <van-dialog v-model="show" title="完成确认" className="sure-dialog" show-cancel-button confirmButtonColor="#3C76FF"
      @confirm="submitAndCompled">
      <div class="model-content">
        <div class="name">是否完成入库单：</div>
        <div class="value">{{ infoData.orderNumber }}</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="submitAndCompled">确认</van-button>
      </div>
    </van-dialog>
    <!-- 打印 -->
    <print v-if="printShow" :isShowPrintNum="printShow" :currentItem="currentItem" :activeTab="activeTab"
      :type="infoData.inOrOutType" @handleConfirmPrint="handleConfirmPrint" @handleCancelPrint="handleCancelPrint">
    </print>
    <!-- 扫码新增批次弹窗 -->
    <material-dialog v-if="materialShow" :show="materialShow" :warehouseCode="infoData.warehouseCode"
      :barCode="materialShowBarcode" :orderNumber="infoData.orderNumber" @handleCancel="materialHandleCancel"
      @handleConfirm="materialHandleConfirm">
    </material-dialog>
    <audio style="display: none" id="audio" ref="audio" src="@/assets/audio/正确.mp3" muted :autoplay="false" />
    <van-dialog v-model="WarehousingShow" className="WarehousingSure-dialog" show-cancel-button
      confirmButtonColor="#3C76FF" :before-close="WarehousingBeforClose" title="入库确认">
      <div class="model-content">
        <div class="name">{{ WarehousingTitle }}</div>
        <div class="value"></div>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="submitAndCompled">确认</van-button>
      </div>
    </van-dialog>
    <BatchListSelectPopupList v-if="showBatchsSelectPopupList" style="height: 70vh" round closeable position="bottom"
      :type="type" :selectBatchs.sync="selectBatchs" v-model="showBatchsSelectPopupList"
      @submitFindSelectedBacths="submitFindSelectedBacths" @handleBatchClose="handleBatchClose">
    </BatchListSelectPopupList>
    <!-- 扫码之前选择供应商或者油漆 -->
    <van-dialog v-model="handleScanCodeRule" className="WarehousingSure-dialog" show-cancel-button
      @confirm="goToScanChange" confirmButtonColor="#3C76FF" title="解码规则">
      <div class="model-content">
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == 'C025'" label="C025"
          style="margin-bottom: 10px;">新鸿洲</el-radio>
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == 'C026'" label="C026"
          style="margin-bottom: 10px;">维科</el-radio>
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == 'C027'" label="C027"
          style="margin-bottom: 10px;">宝利根</el-radio>
        <el-radio v-model="supplierCode" v-if="orderSupplierCode == '' || orderSupplierCode == '1'" label="1" style="margin-bottom: 10px;">油漆</el-radio>
      </div>
      <div slot="footer" class="dialog-footer">
        <van-button round block type="primary" @click="goToScanChange">确认</van-button>
      </div>
    </van-dialog>
  </div>
</template>

<script>
import materialDialog from "@/components/materialDialog";
import print from "./components/print.vue";
import ChoiceSpecificParamsDialog from "@/components/ChoiceSpecificParamsDialog/index.vue";
// import skuDialog from "./components/skuDialog";
import materialList from "./components/materialList";
import listItem from "../allocation/components/listItem.vue";
import materialSearchForm from "./components/materialSearchForm.vue";
import batchSearchForm from "./components/batchSearchForm.vue";
import CommonHeader from "@/components/CommonHeader/index.vue";
import CommonMain from "@/components/CommonMain/index.vue";
import Item from "./components/item.vue";
import addForm from "./components/addForm.vue";
import { Dialog, Toast, Tab, Tabs, Form, Col, Row, version } from "vant";
import {
  deleteMaterialDetails,
  deleteMaterial,
  getStockInAndOutById,
  scanCodeRuleGet,
  pdaScanCodeConfirmation,
  updateRemark,
  configShowConfigGetByKey,
  pdaAddPc,
  reqStateChange,
  getWarehouseUserList
} from "@/api/inventory";
import { allocationGetBarDetails } from "@/api/common";
import {
  getMaterialDetailsList,
  updateMaterialDetails,
  updateMaterial,
  stateChange,
  addMaterialDetails,
  pdaScanCodeMaterial,
  getPdaMaterialList,
  inUpdateMaterialDetails,
  selectLaunchSimultaneouslyCode,
  infoScanInventory,
  getWorkerOrderCodeList,
  newAddBarCode,
  getNewAddBarCodeProgress,
  suppliersMaterialList,
  getNumRuleDetailByType,
  inventoryRelate,
  planNumCompare,
  getUniqueCheck,
  setUniqueCheck,
  materialsList
} from "@/api/inventory";
import { getWarehouseUserInfo, getMaterialWarehouseList, getAllocationStock, getDefaultWarehouse, purchaseStocksInsert, getPurchaseCode, getSuppliers, updateStockInventory,addRelateBarCode, checkBarCode, batchAddBarCode } from '@/api/allocationAdd'
import Decimal from "decimal.js";
import {decodeFun} from './handleBarcodeScan'
export default {
  components: {
    CommonHeader,
    CommonMain,
    Item,
    materialSearchForm,
    batchSearchForm,
    ChoiceSpecificParamsDialog,
    listItem,
    // skuDialog,
    materialList,
    materialDialog,
    [Dialog.Component.name]: Dialog.Component,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Form.name]: Form,
    [Col.name]: Col,
    [Row.name]: Row,
    print,
    MateriaItem: () => import("./components/MateriaItem.vue"),
    BatchListSelectPopupList: () =>
      import("./components/BatchListSelectPopupList.vue"),
    addForm
  },
  data() {
    return {
      SlectedLength: 0,
      materSlectedLength: 0,
      selectInfoList: [],
      WarehousingfilteredData: [],
      WarehousingLength: 0,
      materWarehousingLength: 0,
      WarehousingTitle: "",
      WarehousingShow: false,
      isAllExpand: true,
      isAllExpands: true,
      showBottomMore: false,
      show: false,
      submitLoading1: false,
      /********** */

      /********** */
      showPicker: false,
      searchParams: {
        //onload初始化会调用
        current: 0,
        size: 10,
        dataState: 3,
      },
      searchParams1: {
        current: 0,
        size: 10,
        compositeSearch: "",
      },
      activeTab: 0,
      loading: false,
      finished: false,
      refreshing: false,
      loading1: false,
      finished1: false,
      refreshing1: false,
      isRefreshDisable: false,
      // 滚动与下拉冲突
      scrollTop: 0,
      infoData: {
        isToggle: false,
      },
      search: "",
      skuVsibel: false,
      infoList: [],
      batchList: [], //批次列表
      mqList: [
        { label: "合格", value: 1 },
        { label: "不合格", value: 0 },
      ],
      currentItem: {},
      choiceSpecificParamstVisible: false,
      //打印
      printShow: false,
      planAmountshow: false,
      planAmount: "",
      showRealNum: false,
      realNum: "",
      currentRealItem: {},
      isScan: false, //是否点击了扫码
      materialShow: false,
      materialShowBarcode: "",
      tabs: [
        {
          title: "已选(0/0)",
          isOutbound: "",
          state: "3",
        },
        {
          title: "待入库(0/0)",
          isOutbound: "0",
          state: "1",
        },
        {
          title: "已入库(0/0)",
          isOutbound: "1",
          state: "5",
        },
      ],
      allChecked: false,
      allCheckedSelect: false,
      index: 0,
      dto: [],

      selectBatchs: [],
      showBatchsSelectPopupList: false,
      type: "",
      scanCode: "",
      oldScanCode: {},
      handleScanCodeRule: false, // 选择解码规则弹窗
      supplierCode: '1', // 解码规则-- 的判断条件
      supplierName: '', // 供应商的名称
      orderSupplierCode: '', // 采购入库单原本的物料供应商
      scanMaterDetail: {}, // 当前扫码的物料信息
      isNewMater: false,
      newMaterRelateMaterialId: 0, // 关联物料id的设置基础数字
      supplierInfo: {},
      btnLoading: false,
      defaultScanRes: '',
    };
  },
  watch: {
    selectInfoList: {
      handler(n) {
        let totalCount = 0;
        let total = 0;
        n.forEach((item) => {
          // if (item.stockMaterialDetaiList.some((detail) => detail.checked)) {
          //   total++;
          // }
          item.stockMaterialDetaiList?.forEach((subItem) => {
            if (subItem.checked === true) {
              totalCount++;
            }
          });
          const data = item.stockMaterialDetaiList.filter(
            (item) => item.checked
          );
          const currentTotal = data.reduce((accumulator, currentValue) => {
            return Decimal(accumulator).add(Decimal(currentValue.realNum));
          }, 0);
          total = Decimal(total).add(currentTotal);
        });
        this.WarehousingLength = totalCount;
        this.materWarehousingLength = total.valueOf();
        if (n.length == 0) {
          this.allChecked = false;
        }
        this.allChecked = n.every((item) => item.checked === true);
      },
      deep: true,
    },
    infoList: {
      handler(n) {
        debugger
        let totalCount = 0;
        let total = 0;
        n.forEach((item) => {
          // if (item.stockMaterialDetaiList.some((detail) => detail.checked)) {
          //   total++;
          // }
          item.stockMaterialDetaiList?.forEach((subItem) => {
            if (subItem.checked === true) {
              totalCount++;
            }
          });
          const data = item.stockMaterialDetaiList.filter(
            (item) => item.checked
          );
          const currentTotal = data.reduce((accumulator, currentValue) => {
            return Decimal(accumulator).add(Decimal(currentValue.realNum));
          }, 0);
          total = Decimal(total).add(currentTotal);
        });
        this.SlectedLength = totalCount;
        this.materSlectedLength = total.valueOf();
        if (n.length == 0) {
          this.allCheckedSelect = false;
        }
        this.allCheckedSelect = n.every((item) => item.checked === true);
      },
      deep: true,
    },
    supplierCode(newVal) {
      if (this.supplierCode == '1') return
      this.getSuppliers()
    }
  },
  async created() {
  },
  beforeDestroy() {
    this.$store.dispatch('permission/setbusinessUnitCodeDetail', '')
  },
  mounted() {
    const that = this;
    // PDA扫码
    // window["QrcodeMsg"] = (res) => {
    //   if (res) {
    //     console.log(res, "ScanCodeMsg这是首页");
    //     that.isScan = true;

    //   }
    // };
    // 扫码枪扫码
    window["ScanCodeMsg"] = (res) => {
      if (res) {
        console.log(res, "ScanCodeMsg这是首页");
        this.defaultScanRes = res
        that.isScan = true;
        that.scanBarcodeTrackWithoutNumber(res);
      }
    };
  },
  methods: {
    async getSuppliers() {
      const { data } = await getSuppliers({ currentPage: '1', size: 1, code: this.supplierCode })
      this.supplierInfo = data.data?.records && data.data.records[0] || {}
    },
    async handleDelete() {
      const data = this.infoList
        .flatMap((item) => item.stockMaterialDetaiList)
        .filter((citem) => citem.checked);
      if (data.length == 0) {
        Toast("请至少选择一条数据");
        return;
      }
      const ids = data.map((item) => item.stockMaterialDetailId);
      const result = await deleteMaterialDetails(ids);
      const { code, message } = result.data;
      if (code == 200) {
        Toast("删除成功");
        this.onRefresh();
      } else {
        Toast(message);
      }
    },

    async findList(scanResult) {
      try {
        // 查找物料的批次 -- 找不到就新增，找到了就新增数量
        const infoIndex = this.infoList.findIndex(info => info.code == this.scanMaterDetail.code)
        if (infoIndex != -1) {
          this.isNewMater = false
          // 查找批次 stockMaterialDetaiList 
          let infoItem = this.infoList[infoIndex]
          let isHasStock = infoItem.stockMaterialDetaiList.findIndex(stock => stock.barCode == ((scanResult.supplierMaterialCode || scanResult.materialCode) + scanResult.barCode) )
          console.log(isHasStock,infoItem,infoItem.stockMaterialDetaiList,scanResult.barCode,'000-')
          if (isHasStock != -1) { // 有批次则增加数量
            let oldNum = this.infoList[infoIndex].stockMaterialDetaiList[isHasStock].realNum
            this.$set(this.infoList[infoIndex].stockMaterialDetaiList[isHasStock], 'realNum', Number(oldNum) + Number(scanResult.num))
            const countSum = infoItem.stockMaterialDetaiList.reduce(
              (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
              0
            );
            this.$set(this.infoList[infoIndex],'planAmount',countSum)
            this.$set(this.infoList[infoIndex],'actualAmount',countSum)
            // planAmount += item.count
            // actualAmount += item.count
            // 更新总和 -- 目前不知道放在哪里
            // acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));
          } else {
            //找不到新增批次
            if (scanResult.rule == 1 && this.infoList[infoIndex].isBatchMag) {
              this.isNewMater = false
              this.getInfoScanInventory(scanResult);
            } else {
              Toast.fail("单据无此批次");
            }
          }
        } else {
          // 没找到该物料 --  新增物料 - 在添加批次
          this.isNewMater = true
          // const dataTime = this.formatDate(new Date())
          let dateTime = (new Date()).getTime()
          // this.newMaterRelateMaterialId = Number(String(dateTime).slice(4,dateTime.length))
          let length = this.$refs.addForm.formData.orderNumber.length
          this.newMaterRelateMaterialId = Number(this.$refs.addForm.formData.orderNumber.slice(length-5,length) + '00' + (this.infoList.length + 1))
          console.log(this.newMaterRelateMaterialId,'newMaterRelateMaterialId')
          this.getInfoScanInventory(scanResult)
        }
      } catch (error) {
        //没找到则新增批次
        Toast.fail(error.message);
      }
    },

    async getInfoScanInventory(resdata) {
      try {
        this.type = "新增";
        let barCode = `${resdata.supplierMaterialCode || resdata.materialCode || ''}${resdata.barCode || ''}`
        if(this.supplierCode == 'C027') {
          // 按料号+批号+序号
          barCode = `${resdata.supplierMaterialCode || resdata.materialCode || ''}${resdata.barCode || ''}${resdata.serialNumber || ''}`
        } else if(this.supplierCode == 'C026') {
          // 按料号+序列号
          barCode = `${resdata.supplierMaterialCode || resdata.materialCode || ''}${resdata.serialNumber || ''}`
        }
        this.selectBatchs = [
          {
            barCode,
            materialQuality: 1,
            count: resdata.num,
            produceTime: resdata.produceTime ? this.formatDate(new Date(resdata.produceTime)).formattedDate  : '',
            materialFields: {
              name: this.scanMaterDetail.name,
              code: resdata.materialCode,
              ...this.scanMaterDetail?.materialFields
            },
          },
        ];
        this.selectBatchs.scanObj = resdata;
        console.log(this.selectBatchs, 'selectBatchs-==')
        // this.showBatchsSelectPopupList = true;
        // 直接添加批次
        this.submitFindSelectedBacths(this.selectBatchs)
      } catch (error) {
        Toast.fail(error);
      }
    },
    async inventoryRelate(resdata) {
      const params = { origin: this.scanCode, barCode: `${resdata.supplierMaterialCode || resdata.materialCode}${resdata.barCode}` };
      await inventoryRelate(params);
    },
    async getWorkerOrderCodeList(resdata) {
      let materIndex = this.infoList.findIndex(mater => mater.code == this.scanMaterDetail.code)
      const {
        data: {
          code,
          data: { records = [] },
        },
      } = await getWorkerOrderCodeList({
        current: 1,
        size: 99999,
        materialCode: resdata.materialCode || this.scanMaterDetail.code,
        relateNumber: this.$refs.addForm.formData.orderNumber,
        // barCode: resdata.supplierMaterialCode + resdata.barCode,
        skuId: this.formData?.skuId || 0,
        inventoryDetailId: this.isNewMater ? this.newMaterRelateMaterialId : this.infoList[materIndex].inventoryDetailId || this.scanMaterDetail.id,
      });
      if (code === "200") {
        return records;
      } else {
        return [];
      }
    },
    async getNumRuleDetailByType() {
      const res = await getNumRuleDetailByType({ typeCode: 62 });
      const { data, code, message } = res.data;
      return data;
    },
    // 校验批次是否已经存在
    async getNewAddBarCodeProgress() {
      return new Promise(async (resolve, reject) => {
        const result = await checkBarCode({ 
          barCode: this.selectBatchs[0].barCode,
        });
        const { data, code, message } = result.data;
        let rejectData = [];
        if (code == 200) {
          // 如果data 为空，则表示不存在，可以新增
          if (!data) {
            resolve(1);
          } else {
            reject("已存在该批次");
          }
        }
      });
    },
    handleBatchClose() {
      this.showBatchsSelectPopupList = false;
    },
    async submitFindSelectedBacths(batch) {
      this.addBatch()
      // 不知道以下操作是为了干嘛
      if (this.infoData.supplierCode === 'C027' || this.infoData.supplierCode === 'C026') {
        console.log(this.oldScanCode.supplierMaterialCode, 'rrrrrr')
        // 验证输入数据
        if (!this.oldScanCode || !this.infoData || !this.infoData.orderNumber) {
          console.error('Invalid input data');
          return;
        }
        const { supplierMaterialCode, barCode, serialNumber, num, materialCode } = this.oldScanCode;
        // 检查必要字段是否存在
        if ((!supplierMaterialCode || !materialCode) || !serialNumber || !num) {
          console.error('Missing required fields in scanCode');
          return;
        }
        // 生成 scanCode
        let scanCode;
        if (this.infoData.supplierCode === 'C027') {
          scanCode = (supplierMaterialCode || materialCode) + barCode + serialNumber + num;
        } else {
          scanCode = (supplierMaterialCode || materialCode) + serialNumber + num;
        }
        // 构建参数对象
        const params = {
          orderNumber: this.infoData.orderNumber,
          scanCode
        };
        try {
          // 调用异步方法并处理结果
          const checkData = await setUniqueCheck(params);
          console.log(checkData);
        } catch (error) {
          // 处理异常
          console.error('Error in setUniqueCheck:', error);
        }
      }

    },
    async newAddBarCode(resdata) {
      console.log(this.selectBatchs.scanObj, 'this.selectBatchs.scanObj')
      const numRule = await this.getNumRuleDetailByType();
      let materIndex = this.infoList.findIndex(mater => mater.code == this.scanMaterDetail.code)
      const params = {
        barCode: this.selectBatchs[0].barCode,
        relateNumber: this.$refs.addForm.formData.orderNumber,
        materialCode: resdata.materialCode || this.scanMaterDetail.code,
        moduleType: "purchase",
        num: 1,
        count: resdata.num,
        numberRuleId: numRule[0].id,
        relateMaterialId: this.isNewMater ? this.newMaterRelateMaterialId : this.infoList[materIndex].inventoryDetailId || this.scanMaterDetail.id,
      };
      const res = await newAddBarCode(params);
    },
    async addBatch() {
      // 新增的不添加批次请求
      // await this.newAddBarCode(this.selectBatchs.scanObj);
      try {
        // 校验该批次是否已经添加
        const progress = await this.getNewAddBarCodeProgress(
          this.selectBatchs.scanObj
        );
        if (progress == 1) {
          const records = await this.getWorkerOrderCodeList(
            this.selectBatchs.scanObj
          );
          const { warehouseEntity } = this.scanMaterDetail
          let materIndex = this.infoList.findIndex(mater => mater.code == this.scanMaterDetail.code)
          let item = this.selectBatchs[0]
          const stockMaterialDetaiItem = {
              isAdd: true,
              // ...item,
              materialCode: this.scanMaterDetail.materialCode,
              // skuId: item.skuId,
              skuCode: this.scanMaterDetail?.materialFields
                ? this.scanMaterDetail?.materialFields.skuEntity?.skuCode
                : "",
              skuName: this.scanMaterDetail?.materialFields ? this.scanMaterDetail?.materialFields.skuEntity?.skuName : "",
              barCode: this.selectBatchs[0].barCode,
              materialQuality: this.scanMaterDetail?.materialQuality || "1",
              realNum: this.selectBatchs[0].count || 0,
              remark: "",
              isNewAdd: true,
              inventoryDetailId: this.isNewMater ? this.newMaterRelateMaterialId : this.infoList[materIndex].inventoryDetailId || this.scanMaterDetail.id,
              planNum: 0,
              produceTime: this.selectBatchs[0].produceTime || '',
              stockInventoryDetailEntity: {
                produceTime: this.selectBatchs[0].produceTime || '',
                planNum: 0,
                adjustInNumber: 0,
                adjustOutNumber: 0,
                allotInNumber: 0,
                allotOutNumber: 0,
                availableStock: 0,
                barCode: item.barCode,
                count: item.count || 0,
                createTime: item.createTime,
                currentInventory: 0,
                inventoryDetailId: this.isNewMater ? this.newMaterRelateMaterialId : this.infoList[materIndex].inventoryDetailId || this.scanMaterDetail.id,// 有点对不上
                inventoryPendingEntry: 0, // 计划入库数量
                inventoryPendingListing: 0, // 待入库数量 ？？ 
                isStack: 0, // ？
                relateNumber: item.relateNumber,
                shiftInNumber: 0,
                shiftOutNumber: 0,
                shipperCode: null,
                shipperName: null,
                skuCode: item.skuCode || '',
                // skuId: item.skuId,
                skuName: "",
                sourceBatch: null,
                // state: item.state,
                // stateName: item.stateName,
                stayDeliveryStock: 0,
                stockAgeWarning: null,
                stockDuration: null,
                stockInAndOutEntity: null,
                stockInventoryRecordEntityList: null,
                stockLocationName: null,
                stockLocationNum: null,
                stockLocationQuantity: 0,
                stockMaterialDetailId: null,
                stockMaterialDetailSate: null,
                stockMaterialId: null,
                stockMaters: null,
                stocktakingLossNumber: 0,
                stocktakingMakeNumber: 0,
                supplier: null,
                supplierCode: null,
                supplierName: null,
                totalQuantity: null,
                unit: null,
                upRealNum: null,
                updateBy: null,
                updateTime: "",
                warehouseCode: warehouseEntity.warehouseCode,
                warehouseExist: null,
                warehouseId: warehouseEntity.warehouseId,
                warehouseName: warehouseEntity.warehouseName,
                warehouseType: warehouseEntity.warehouseType,
                warehouseTypeName: warehouseEntity.warehouseTypeName,
                warehousingDate: null,
              }
          }

          if (this.isNewMater) {
            let materItem = {
              ...this.scanMaterDetail,
              ...this.scanMaterDetail?.materialFields,
              stockMaterialDetaiList: [stockMaterialDetaiItem],
              isExpand: true,
              materialFields: this.scanMaterDetail?.materialFields,
              materialEntity: { ...this.scanMaterDetail?.materialFields },
              inventoryDetailId: this.newMaterRelateMaterialId,
              supplierName: this.supplierInfo.name,
              planAmount: Number(this.selectBatchs[0].count),
              actualAmount: Number(this.selectBatchs[0].count),
            }
            this.$nextTick(() => {
              this.infoList.push(materItem)
              console.log(this.infoList,this.supplierInfo,'inforList--=')
            })
          } else {
            this.infoList[materIndex].stockMaterialDetaiList.push(stockMaterialDetaiItem)
            // this.$set(this.infoList[materIndex], 'stockMaterialDetaiList', stockMaterialDetaiList)
            let planAmount = Number(this.infoList[materIndex].planAmount) + Number(this.selectBatchs[0].count)
            let actualAmount = Number(this.infoList[materIndex].actualAmount) + Number(this.selectBatchs[0].count)
            this.$set(this.infoList[materIndex], 'planAmount', planAmount)
            this.$set(this.infoList[materIndex], 'actualAmount', actualAmount)
          }
          if (this.supplierCode === 'C027' || this.supplierCode === 'C026') {
            // 生成 scanCode
            const {supplierMaterialCode ,barCode, serialNumber, num, materialCode} = this.selectBatchs.scanObj
            let scanCode = this.supplierCode === 'C027' ? ((supplierMaterialCode || materialCode) + barCode + serialNumber + num) :  ((supplierMaterialCode || materialCode) + serialNumber + num)
            // 保存扫码结果，以便判断唯一
            const params = {
              orderNumber: this.$refs.addForm.formData.orderNumber,
              scanCode
            };
            // 调用异步方法并处理结果
            const checkData = await setUniqueCheck(params);
            console.log(checkData);
          }
          console.log(this.infoList, 'liebiao')
          this.showBatchsSelectPopupList = false;
          await addRelateBarCode({origin: this.defaultScanRes,
            barCode: this.selectBatchs[0].barCode})
          Toast("添加成功");
        } else {
          throw new Error("批次新增异常！");
        }
      } catch (error) {
        Toast.fail(error);
        console.log(error, 'error')
      }
    },
    handleAddSelectInfoList() {
      let data = this.infoList.map((item) => {
        return {
          ...item,
          stockMaterialDetaiList: item.stockMaterialDetaiList.filter(
            (detail) => detail.checked !== false
          ),
        };
      });
      data = data.filter((item) => item.stockMaterialDetaiList.length != 0);
      //有全选选中的物料
      let isFirstLevelCheckedTrue = this.infoList.some(
        (item) =>
          item.checked === true && item.stockMaterialDetaiList.length === 0
      );
      if (this.selectInfoList.length == 0) {
        data.map((item) => {
          item.checked = true;
          item.stockMaterialDetaiList.map((citem) => {
            citem.checked = true;
          });
        });
        this.selectInfoList.push(...data);
      } else {
        data.forEach((bItem) => {
          // 在 a 数组中查找匹配的项
          let matchingItem = this.selectInfoList.find(
            (aItem) =>
              aItem.id === bItem.id &&
              aItem.materialEntity.code === bItem.materialEntity.code &&
              aItem.skuId === bItem.skuId
          );
          // 如果找到匹配项
          if (matchingItem) {
            // 遍历 bItem 的 stockMaterialDetaiList
            bItem.stockMaterialDetaiList.forEach((bDetail) => {
              // 在 aItem 的 stockMaterialDetaiList 中查找相同的 inventoryDetailId 的索引
              let aDetailIndex = matchingItem.stockMaterialDetaiList.findIndex(
                (aDetail) =>
                  aDetail.inventoryDetailId === bDetail.inventoryDetailId
              );

              // 如果找到相同的 inventoryDetailId
              if (aDetailIndex !== -1) {
                bDetail.checked = true;
                // 替换相同 inventoryDetailId 的项
                matchingItem.stockMaterialDetaiList.splice(
                  aDetailIndex,
                  1,
                  bDetail
                );
              } else {
                // 如果没有找到相同 inventoryDetailId，则添加到 aItem 的 stockMaterialDetaiList 中
                bDetail.checked = true;
                matchingItem.stockMaterialDetaiList.push(bDetail);
              }
            });
          } else {
            bItem.checked = true;
            bItem.stockMaterialDetaiList.map((citem) => {
              citem.checked = true;
            });
            // 如果没有找到匹配项，则将整个 bItem 添加到 a 数组中
            this.selectInfoList.push(bItem);
          }
        });
      }
      //先赋予初值
      this.selectInfoList.forEach((item) => {
        console.log();
        this.$set(item, "isExpand", true);
        this.$set(item, "checked", item.checked);
        item.stockMaterialDetaiList.map((citem) => {
          this.$set(citem, "checked", citem.checked);
        });
      });
      const result = this.selectInfoList.reduce(
        (acc, current) => {
          const stockMaterialDetaiList = current.stockMaterialDetaiList;

          // 计算 stockMaterialDetaiList 的长度
          const listLength = stockMaterialDetaiList.length;

          // 计算 count 的总和
          const countSum = stockMaterialDetaiList.reduce(
            (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
            0
          );

          // 更新累积的长度和总和
          acc.lengthSum += listLength;
          acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

          return acc;
        },
        { lengthSum: 0, countSum: Decimal(0) }
      );

      this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
      this.selectInfoList.splice();
      this.searchParams.dataState = "3";
      this.$nextTick(() => {
        setTimeout(() => {
          document.getElementById("Material" + data[0].id).scrollIntoView();
        });
      });
      let msg = isFirstLevelCheckedTrue
        ? "选中的数据有无批次数据已被过滤"
        : "已移入已选";
      Toast(msg);
    },
    updateSingleMaterial() {
      this.selectInfoList.splice();
    },
    handleConfirmWarehousing() {
      if (this.searchParams.dataState != 3) {
        return;
      }
      const filteredData = this.selectInfoList
        .map((item) => ({
          ...item,
          stockMaterialDetaiList: Array.isArray(item.stockMaterialDetaiList)
            ? item.stockMaterialDetaiList.filter(
              (subItem) => subItem.checked !== false
            )
            : [],
        }))
        .filter(
          (item) =>
            item.checked === true || item.stockMaterialDetaiList.length > 0
        );
      console.log("data", filteredData);
      if (filteredData.length == 0) {
        Toast({
          className: "myToast jinggao",
          message: "请至少勾选一条数据",
          position: "top",
        });
      } else {
        let indexs = [];
        for (let i = 0; i < filteredData.length; i++) {
          for (let j = 0; j < this.selectInfoList.length; j++) {
            if (filteredData[i].id == this.selectInfoList[j].id) {
              indexs.push(j);
              break;
            }
          }
        }
        console.log("this.$refs.MateriaItem[item]", this.$refs.MateriaItem[0]);
        const validatePromises = indexs.map((item) => {
          return new Promise((resolve, reject) => {
            console.log(
              "this.$refs.MateriaItem",
              item,
              this.$refs.MateriaItem[item].$refs
            );
            this.$refs.MateriaItem[
              item
            ].$refs.materialtable.$refs.form.validate((valid) => {
              console.log("validvalidvalid", valid);
              if (valid) {
                resolve();
              } else {
                reject();
              }
            });
          });
        });
        Promise.all(validatePromises)
          .then((results) => {
            this.WarehousingfilteredData = filteredData;
            this.WarehousingBeforClose("confirm", function () { });
            // console.log("resultsresultsresults", results);
            // this.WarehousingShow = true;

            // this.WarehousingTitle = filteredData.some(
            //   (item) =>
            //     !item.stockMaterialDetaiList ||
            //     item.stockMaterialDetaiList.length === 0
            // )
            //   ? "入库单无此物料或批次信息，请确认!"
            //   : "是否确认当前勾选物料入库";
          })
          .catch((err) => { });
      }
    },
    async WarehousingBeforClose(action, done) {
      if (action == "confirm") {
        const params = this.WarehousingfilteredData.flatMap(
          ({ stockMaterialDetaiList }) =>
            stockMaterialDetaiList.map((item) => ({
              ...item,
              dataState: 5,
            }))
        );
        const result = await inUpdateMaterialDetails(params);

        const remarks = this.WarehousingfilteredData.map((item) => {
          return {
            id: item.id,
            materialRemark: item.materialRemark,
          };
        });
        await updateRemark(remarks);

        const { data, code, message } = result.data;
        if (code == 200) {
          this.selectInfoListHandleDelelte();
          this.searchParams.dataState = "5";

          const getSimultaneouslyData = await selectLaunchSimultaneouslyCode(
            "auto_complete_purchase",
            this.infoData.orderNumber
          );
          const { data: Simultaneously } = getSimultaneouslyData.data;

          if (Simultaneously) {
            await this.changeState(this.$route.query.id, 2);
          }
          done();
          this.onRefresh();
        } else {
          Toast.fail(message);
          done();
        }
      } else {
        done();
      }
    },
    async changeState(id, state) {
      const res = await stateChange({ id, state });
      let { data } = res;
    },
    selectInfoListHandleDelelte() {
      // 找到在a数组中与b数组中id相同的项
      let matchingItems = this.selectInfoList.filter((aItem) =>
        this.WarehousingfilteredData.some((bItem) => aItem.id === bItem.id)
      );

      // 遍历匹配的项
      matchingItems.forEach((matchingItem) => {
        // 在a数组里面stockMaterialDetaiList里面的inventoryDetailId相等的项删除
        matchingItem.stockMaterialDetaiList =
          matchingItem.stockMaterialDetaiList.filter((aDetail) => {
            let bItem = this.WarehousingfilteredData.find(
              (bItem) => bItem.id === matchingItem.id
            );
            if (bItem) {
              return !bItem.stockMaterialDetaiList.some(
                (bDetail) =>
                  bDetail.inventoryDetailId === aDetail.inventoryDetailId
              );
            }
            return true;
          });
      });

      // 删除stockMaterialDetaiList的长度为0的项
      this.selectInfoList = this.selectInfoList.filter(
        (aItem) => aItem.stockMaterialDetaiList.length > 0
      );
      this.$refs.MateriaItem.forEach((item) => {
        console.log("item", item.$refs.materialtable);
        item.$refs.materialtable.updataTable();
      });
      const result = this.selectInfoList.reduce(
        (acc, current) => {
          const stockMaterialDetaiList = current.stockMaterialDetaiList;

          // 计算 stockMaterialDetaiList 的长度
          const listLength = stockMaterialDetaiList.length;

          // 计算 count 的总和
          const countSum = stockMaterialDetaiList.reduce(
            (sum, item) => Decimal(sum).add(Decimal(item.realNum)),
            0
          );

          // 更新累积的长度和总和
          acc.lengthSum += listLength;
          acc.countSum = Decimal(acc.countSum).add(Decimal(countSum));

          return acc;
        },
        { lengthSum: 0, countSum: Decimal(0) }
      );

      this.tabs[0].title = `已选(${result.lengthSum}/${result.countSum})`;
    },
    allExpandOrFold() {
      this.isAllExpand = !this.isAllExpand;
      this.selectInfoList.map((item) => {
        if (this.isAllExpand) {
          item.isExpand = true;
        } else {
          item.isExpand = false;
        }
      });
    },
    allExpandOrFolds() {
      this.isAllExpands = !this.isAllExpands;
      this.infoList.map((item) => {
        if (this.isAllExpands) {
          item.isExpand = true;
        } else {
          item.isExpand = false;
        }
      });
    },
    allSelect() {
      this.selectInfoList.map((item) => {
        item.checked = true;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = true;
        });
      });
      this.selectInfoList.slice();
    },
    allSelectcanel() {
      this.selectInfoList.map((item) => {
        item.checked = false;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = false;
        });
      });
      this.selectInfoList.slice();
    },
    allSelectdataState() {
      this.infoList.map((item) => {
        item.checked = true;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = true;
        });
      });
      this.infoList.splice();
    },
    allSelectcaneldataState() {
      this.infoList.map((item) => {
        item.checked = false;
        item.stockMaterialDetaiList.map((citem) => {
          citem.checked = false;
        });
      });
      this.infoList.splice();
    },
    updateMaterialExpand(val) { },
    updateMaterialRemark() { },
    // 播放音频
    playAudio(isSuccess) {
      // const audioElement = document.getElementById('audio')
      const audioElement = this.$refs.audio;
      // audioElement
      audioElement.src = isSuccess
        ? require("@/assets/audio/正确.mp3")
        : require("@/assets/audio/错误.mp3");
      this.$nextTick(() => {
        try {
          audioElement.paused && audioElement.play();
        } catch (error) {
          console.log(error);
        }
      });
    },
    // 解码 refund-outbound-app.material-out.handleScanCode.barCode
    async scanCodeRuleGet(scanCode) {
      try {
        const params = {
          code: "purchaseWarehousing.handleBarcodeScan.new",
        };
        const {
          data: { code, data },
        } = await scanCodeRuleGet(params);
        if (code === "200") {
          // 如果有配置解码规则
          if (data.value) {
            const fn = new Function(`return ${data.value}`)();
            const result = fn(scanCode, this.supplierCode || "");
            // const result = decodeFun(scanCode, this.supplierCode || "");
            console.log(result, 'result---解码后的结果')
            this.scanCode = scanCode;
            this.oldScanCode = result
            //   this.playAudio(true);
            return result;
          } else {
            //  this.playAudio(true);
            return scanCode;
          }
        }
      } catch (error) {
        this.playAudio(false);
        console.log(error, '=====')
        return "";
      }
    },

    // 扫码解码
    async scanBarcodeTrackWithoutNumber(res) {
      if (!this.orderSupplierCode) {
        return this.handleScanCodeRule = true
      }
      this.orderSupplierCode = this.supplierCode
      if(this.orderSupplierCode == 'C025') { // 新鸿洲包含#号
        let flag = res.indexOf('.')
        if(flag <= -1) {
          return  Toast.fail('不是该供应商的码，请重新扫码')
        }
      } else if(this.orderSupplierCode == 'C026') {  // 维科不包含 # 号
        let flag = res.indexOf('.')
        if(flag > -1) {
          return  Toast.fail('不是该供应商的码，请重新扫码')
        }
      }
      const that = this;
      let orderNumber =  this.$refs.addForm.formData.orderNumber
      const scanResult = await this.scanCodeRuleGet(res);
      console.log(scanResult, '解码规则接出来的结果')
      if(this.supplierCode == 'C027' || this.supplierCode == 'C026') {
        let scanCode = this.supplierCode == 'C027' ? ((scanResult.supplierMaterialCode || scanResult.materialCode) + scanResult.barCode + scanResult.serialNumber + scanResult.num) : ((scanResult.supplierMaterialCode || scanResult.materialCode) + scanResult.serialNumber + scanResult.num)
        let params = {
          orderNumber: orderNumber,
          scanCode
        }
        const checkData = await getUniqueCheck(params)
        console.log(checkData,'判断唯一性')
        if(checkData.data.code == 200) {
          if(!checkData.data.data) { // 如果是false ，则表示重复了
            Toast.fail('不允许重复扫入批次，请重新扫码')
            return
          }
        }
      }
      // 查询物料信息
      let params = {
        code: scanResult.supplierMaterialCode || scanResult.materialCode,
        current: 1,
        materialFields: {
          code: scanResult.supplierMaterialCode || scanResult.materialCode,
        },
        size: 10,
        states: '2'
      }
      try {
        const res = await materialsList(params);
        let { records: data } = res.data.data
        console.log(data, ' 查询到的物料信息')
        if (data && data.length > 0) {
          // let supplierName = 
          let warehouseParams = { productCode: scanResult.supplierMaterialCode || data.code || scanResult.materialCode, skuId: 0 }
          //查询仓库物料的信息 --- 目前不知道放到哪里
          const defaultWarehouse = await getDefaultWarehouse(warehouseParams) // 查询默认仓库
          const warehouseEntities = defaultWarehouse.data?.data || []
          const allocationStock = await getAllocationStock({ code: scanResult.supplierMaterialCode || data.code || scanResult.materialCode , skuId: 0 },warehouseEntities[0].warehouseId)
          const MaterialWarehouseList = await getMaterialWarehouseList(warehouseParams)
          const warehouseUserList = await getWarehouseUserList(warehouseEntities[0].warehouseId)
          const warehouseList = MaterialWarehouseList.data?.data || []
          this.scanMaterDetail = { ...data[0], warehouseList,warehouseEntitiesDown:warehouseList, warehouseEntities, warehouseEntity:warehouseEntities[0] || {} ,warehouseUserList: warehouseUserList.data.data }
          console.log(this.scanMaterDetail, 'scanMaterDetail')
          // 添加批次
          this.findList(scanResult);
        } else {
          Toast.fail('该码的物料不在系统内');
        }
      } catch (err) {
        Toast.fail(err);
        console.log(err, 'err')
      }
    },
    async planNumCompare(num, productCode) {
      const params = {
        inOrOutType: this.infoData.inOrOutType,
        orderId: this.$route.query.id,
        productCode: productCode,
        num: num
      }
      const res = await planNumCompare(params)
      const { code, message, data } = res.data
      if (code != 200) {
        Toast.fail(message)
      }
      return code
    },
    selectAllTextPlan() {
      this.$refs.planNumInput.$refs.input.select();
    },
    selectAllTextReal() {
      this.$refs.realNumInput.$refs.input.select();
    },
    materialHandleCancel() {
      this.materialShow = false;
      this.isScan = false;
      // 取消搜索
      if (this.activeTab == 0) {
        this.searchParams.productCode = "";
        this.materialShowBarcode = "";
        this.onRefresh();
      } else {
        this.searchParams1.compositeSearch = "";
        this.materialShowBarcode = "";
        this.onRefresh1();
      }
    },
    // 新增批次确认按钮事件
    async materialHandleConfirm(paramsData) {
      await this.materialSubmit(paramsData);
      this.materialShow = false;
      this.isScan = false;
      if (this.activeTab == 0) {
        this.onRefresh();
      } else {
        this.onRefresh1();
      }
    },
    async materialSubmit(paramsData) {
      const { form, records } = paramsData || {};
      const datas = {
        productCode: form.productCode,
        skuId: form.skuId,
        skuCode: form.skuCode,
        skuName: form.skuName,
        materialType: form.materialType,
        type: form.type,
        actualNum: "",
      };
      const stockMaterialDetaiList = records.map((item) => {
        return {
          materialCode: form.productCode,
          skuId: item.skuId,
          skuCode: item.materialFields
            ? item.materialFields.skuEntity?.skuCode
            : "",
          skuName: item.materialFields
            ? item.materialFields.skuEntity?.skuName
            : "",
          barCode: item.barCode,
          materialQuality: form.materialQuality || "1",
          realNum: form.realNum,
          // saleMaterialId: this.$route.query.id,
          remark: "",
          isNewAdd: true,
          inventoryDetailId: item.inventoryDetailId || "",
        };
      });
      const materialDetails = {
        ...datas,
        materialQuality: form.materialQuality,
        stockMaterialDetaiList: stockMaterialDetaiList || [],
      };
      const param = {
        id: this.$route.query.id || null,
        materialDetails: [materialDetails],
      };
      const result = await addMaterialDetails(param);
      const { code, message, data } = result.data;
      if (code == 200) {
        this.$emit("handleConfirm");
      } else {
        throw new Error("批次新增异常！");
      }
    },
    // 实际数量修改
    realNumDialog(item) {
      if (!(this.infoData.state == 0 || this.infoData.state == 1)) {
        return;
      }
      const obj = JSON.parse(JSON.stringify(item));
      this.currentRealItem = item;
      this.realNum = obj.realNum;
      this.showRealNum = true;
    },
    realNumHandleConfirm() {
      this.$refs.realNumForm
        .validate("realNum")
        .then(async (res) => {
          this.currentRealItem.realNum = this.realNum;
          this.showRealNum = false;
          this.currentRealItem = {};
          await this.updateMaterialDetails(this.batchList);
        })
        .catch((err) => {
          this.showRealNum = true;
        });
    },
    realNumHandleCancel() {
      this.currentRealItem = {};
      this.showRealNum = false;
    },
    beforClose(action, done) {
      if (action == "confirm") {
        if (!this.planAmountshow) {
          done();
        } else {
          done(false);
        }
      } else {
        done();
      }
    },
    numHandleConfirm() {
      this.$refs.planAmountForm.validate("planAmount").then((res) => {
        this.currentItem.planAmount = this.planAmount;
        this.planAmountshow = false;
        this.currentItem = {};
        this.updateMaterial(this.infoList);
      });
    },
    numHandleCancel() {
      this.currentItem = {};
      this.planAmountshow = false;
    },
    handleConfirmPrint() {
      this.printShow = false;
    },
    handleCancelPrint() {
      this.printShow = false;
    },
    printDialog(item) {
      const hasCheckedLength = item.stockMaterialDetaiList.filter(
        (item) => item.checked
      );
      if (hasCheckedLength == 0) {
        Toast("请至少选中一条数据");
        return;
      }
      this.printShow = true;
      this.currentItem = item;
    },
    getPlanAmount(item) {
      return [
        {
          item,
          validator: this.validatorPlanAmount,
          message: "计划数量不能为空,不能小于等于0",
          trigger: "onBlur",
        },
      ];
    },
    getRealNum(item) {
      return [
        {
          item,
          validator: this.validatorRealNum,
          message: "实际数量不能为空,不能小于等于0",
          trigger: "onBlur",
        },
      ];
    },
    validator(val, rule) {
      if (!val) {
        return false;
      }
      if (val <= 0) {
        return false;
      } else {
        return true;
      }
    },
    validatorPlanAmount(val, rule) {
      if (!val) {
        return false;
      }
      if (val < 0) {
        return false;
      } else {
        return true;
      }
    },
    validatorRealNum(val, rule) {
      if (!val) {
        return false;
      }
      if (val <= 0) {
        return false;
      } else {
        return true;
      }
    },
    confirmChoiceSpecificParams(data) {
      this.skuData.skuId = data.skuId;
      this.skuData.skuCode = data.skuCode;
      this.skuData.skuName = data.skuName;
      this.choiceSpecificParamstVisible = false;
    },
    cancelChoiceSpecificParams() {
      this.choiceSpecificParamstVisible = false;
    },
    deleteMaterial(id) {
      this.isScan = false;
      Dialog.confirm({
        title: "删除",
        message: "确认删除此物料",
        confirmButtonColor: "#548AF1",
      }).then(async () => {
        // on confirm
        await deleteMaterial({ materialId: id });
        this.onRefresh();
      });
    },
    deleteMaterialDetails(id) {
      this.isScan = false;
      Dialog.confirm({
        title: "删除",
        message: "确认删除此批次",
        confirmButtonColor: "#548AF1",
      }).then(async () => {
        // on confirm
        await deleteMaterialDetails([id]);
        this.onRefresh1();
      });
    },
    updateMaterialDetails(data) {
      return new Promise(async (resolve, reject) => {
        try {
          const {
            data: { code, data: data1 },
          } = await updateMaterialDetails(data);
          if (code == 200) {
            // console.log(data1, "data1");

            // this.batchList.forEach(i)
            data1.forEach((i) => {
              const index = this.batchList.findIndex(
                (batch) =>
                  batch.stockMaterialDetailId === i.stockMaterialDetailId
              );
              if (index > -1) {
                this.batchList[index].version = i.version;
              }
            });
            Toast.success("提交成功");
            resolve();
          }
        } catch (error) {
          this.onRefresh1();
        }
      });
    },
    updateMaterial(data) {
      return new Promise(async (resolve, reject) => {
        const {
          data: { code },
        } = await updateMaterial(data);
        if (code == 200) {
          Toast.success("提交成功");
          resolve();
        }
      });
    },
    materialDialogShow() {
      this.materialShow = true;
    },
    async getMaterialDetailsList() {
      const params = {
        ...this.searchParams1,
        orderNumber: this.infoData.orderNumber,
      };
      this.loading1 = true;
      this.refreshing1 = true;
      const {
        data: {
          data: { records, total },
        },
      } = await getMaterialDetailsList(params);
      this.loading1 = false;
      this.refreshing1 = false;
      if (records) {
        records.map((item) => {
          item.stockInventoryDetailEntity.materialQualityName =
            item.stockInventoryDetailEntity.materialQuality == 1
              ? "合格"
              : "不合格";
        });
      }
      if (this.searchParams1.current > 1) {
        this.batchList = [...this.batchList, ...records];
      } else {
        this.batchList = records;
      }
      if (this.infoData.state != 2) {
        if (this.isScan) {
          if (this.batchList.length == 0) {
            this.materialDialogShow();
          } else {
            this.isScan = false;
          }
        }
      }

      if (this.batchList.length >= total) {
        this.finished1 = true;
      }
    },
    async configShowConfigGetByKey(orderType) {
      const res = await configShowConfigGetByKey(orderType);
      const { code, data, message } = res.data;
      return data.propertyValue;
    },

    goToScanChange() {
      this.orderSupplierCode = this.supplierCode
      this.scanBarcodeTrackWithoutNumber(this.defaultScanRes);
    },
    scanChange() {
      const that = this;
      that.isScan = true;
      this.index++;
      if (process.env.NODE_ENV === "development") {
        let newTime = (new Date()).getTime()
        let a = [
          "2302198016665-W230106049;SX;10;CKPC123456",
          "2302198016665-W230106045;SX;10;CKPC123456",
          "2302198016665-W230106047;SX;10;CKPC123457",
          "2302198016665-W230106049;8600175;10;CKPC" + newTime,
          "2302198016665-W230106048;8600175;10;CKPC" + newTime,
          "HW-UV9100-2/A-202413810/13/2024-8-31",
          "GN266XA;SX;HSG,BOT,CAMBRIDGERIE312GRY#3;CKPC20241202039;100;ABS/19878400;00071449-P;B.1;13",
          "10@SX@B_2-03035-000193#CKPC20241202020#0515",
          "GN266XA;SX;HSG,BOT,CAMBRIDGERIE312GRY#3;CKPC20241202037;100;ABS/19878400;00071449-P;B.1;13",
          "test0328-txcs/kg000120240523123/20",
          "test0328-txcs/kg000120240523123/20",
          "2302198016665-W230106090;SX;10;CKPC" + newTime,
          "2302198016665-W230106090;8600175;10;CKPC" + newTime,
          "2302198016665-W230106011;SX;10;CKPC20241202023",
          "2302198016665-W230106012;SX;10;CKPC20241202024",
          "2302198016665-W230106013;SX;10;CKPC20241202025",
          "200@test-1845-ceshi@#CK202407160002#",
          "boli",
          "boli",
          "100@XYD-TOM100100@#CK2024070801212#",
          "200@test-1845-ceshi@#CK202407160002#",
          "20240202-CGSH013",
        ];
        this.defaultScanRes = a[this.index - 1]
        that.scanBarcodeTrackWithoutNumber(a[this.index - 1]);
        // that.decodeFun(a[this.index - 1]);
      } else {
        window.flutter_inappwebview.callHandler("qrCode").then((res) => {
          if (res) {
            this.defaultScanRes = res
            console.log(res, "qrCode");
            that.scanBarcodeTrackWithoutNumber(res);
          }
        });
      }
    },
    // 点击picker取消按钮
    onCancel() {
      this.showPicker = false;
    },
    // 点击picker确定按钮
    onConfirm(e) {
      this.currentItem.stockInventoryDetailEntity.materialQuality = e.value;
      this.currentItem.stockInventoryDetailEntity.materialQualityName = e.label;
      console.log(this.currentItem);
      this.showPicker = false;
    },

    //提交并完成
    async submitAndCompled() {
      if (this.activeTab == 0) {
        this.submitLoading1 = true;
        await this.updateMaterial(this.infoList);
        const {
          data: { code, message },
        } = await stateChange({
          id: this.$route.query.id,
          state: 2,
          type: "purchase",
        });
        if (code == 200) {
          this.$router.push("/allocation");
        } else {
          Toast(message);
        }
        this.submitLoading1 = false;
      } else {
        this.submitLoading1 = true;
        this.$refs.vantForm
          .validate()
          .then(async () => {
            await this.updateMaterialDetails(this.batchList);
            const {
              data: { code },
            } = await stateChange({
              id: this.$route.query.id,
              state: 2,
              type: "purchase",
            });
            if (code == 200) {
              this.$router.push("/allocation");
            }
            this.submitLoading1 = false;
          })
          .catch(() => {
            this.submitLoading1 = false;
          });
      }
    },
    //提交并完成
    async submit() {
      if (this.activeTab == 0) {
        await this.updateMaterial(this.infoList);
        this.$router.push("/allocation");
      } else {
        this.$refs.vantForm.validate().then(async () => {
          await this.updateMaterialDetails(this.batchList);
          this.$router.push("/allocation");
        });
      }
    },
    // 加载更多
    onLoad() {
      console.log("滚到了底部");
    },
    // 下拉刷新
    onRefresh() {
    },
    onRefresh1() {
      // 清空列表数据
      this.finished1 = false;
      this.searchParams1.current = 1;
      this.getMaterialDetailsList();
    },
    skuDialog(data) {
      console.log(data, "=====");
      this.choiceSpecificParamstVisible = true;
      this.skuData = data;
    },
    formatDate(val) {
      const date = new Date(val);
      const Y = date.getFullYear();
      const M = date.getMonth() + 1;
      const D = date.getDate();
      const H = date.getHours();
      const Min = date.getMinutes();
      const S = date.getSeconds();
      const mY = String(Y).substring(2, 4)
      const formattedDate = `${Y}-${(M < 10 ? '0' : '') + M}-${(D < 10 ? '0' : '') + D} ${(H < 10 ? '0' : '') + H}:${(Min < 10 ? '0' : '') + Min}:${(S < 10 ? '0' : '') + S}`;
      const formatDate = `${(M < 10 ? '0' : '') + M}${(D < 10 ? '0' : '') + D}${(H < 10 ? '0' : '') + H}${(Min < 10 ? '0' : '') + Min}${(S < 10 ? '0' : '') + S}`;
      const formatDateNum = Number(formatDate)
      return { formattedDate, formatDateNum }
    },
    /**
     * 新增提交事件
     * 1、先，生成采购订单号
     * 2、新增采购订单，关联订单
     * 3、批量添加批次
     * 4、新增采购入库单 -- 请求成功
     * 5、修改入库单状态为生效 
     */
    async confirmWarehousing() {
      const valid = this.$refs.addForm.submitAdd()
      console.log(valid, 'valid-----==')
      if (valid) {
        if (this.infoList && this.infoList.length <= 0) {
          Toast.fail('请扫码添加物料');
          return
        }
        try {
          // 1、生成订单号
          let purchaseCode = await this.getPurchaseCodes()
          console.log(purchaseCode,'生成的订单号')
          console.log(this.infoList,'infoList')
          if(!purchaseCode) return
          // 2、新增采购订单 -- 只需要物料
          let materList = this.infoList.map(mater => {
            // 计算入库数量
            let planNum = 0
            mater.stockMaterialDetaiList.forEach(stock => { 
              planNum += Number(stock.realNum)
            })
            return {
              code: mater.code,
              planNum: planNum
            }
          })
          let realTime = this.formatDate(new Date()).formattedDate
          let insertParams = {
            purchaseCode: purchaseCode,
            purchaseType: 0,
            realTime: realTime,
            requestMaterialEntities: materList,
            supplierCode: this.supplierCode,
            supplierName: this.supplierInfo.name,
            buyer: this.$refs.addForm.formData.applyPersonName
          }
          const data = await purchaseStocksInsert(insertParams)
          // 查询订单详情
          
          if (data.data.code == 200) {
            // 3、批量新增批次 4、新增采购入库单
            this.addPda(purchaseCode,materList)
          }
        } catch (error) {
          Toast.fail(error);
          console.log(error, '新增提交')
        }
      }
    },
    // 生成采购订单编号
    async getPurchaseCodes() {
      try {
        const {data} = await getPurchaseCode()
        return data.data
      } catch (error) {
        Toast.fail(error);
      }
    },
    // 批量新增批次
    async addAllBarCode() {
      
    },
    // 新增采购入库单操作 - 修改状态，跳转到编辑页面
    async addPda(purchaseCode,materList) {
      const numRule = await this.getNumRuleDetailByType();
      this.btnLoading = true
      let formData = this.$refs.addForm.formData
      let stockParams = []
      let barCodeLsit = []
      let materialDetails = this.infoList.map( (item,inforIndex) => {
        item.stockMaterialDetaiList.forEach( stockitem => {
          let stockItem = {
            relateNumber: formData.orderNumber,
            barCode:  stockitem.barCode,
            productCode: item.code,
            produceTime: stockitem.produceTime
          }
          stockParams.push(stockItem)
          barCodeLsit.push({
            barCode: stockitem.barCode,
            relateNumber: formData.orderNumber,
            materialCode: item.code,
            moduleType: "purchase",
            num: 1,
            count: stockitem.realNum,
            numberRuleId: numRule[0].id,
            relateMaterialId: item.inventoryDetailId,
          })
        })
        return {
          ...item,
          productCode: item.code,
          planAmount: materList[inforIndex].planNum,
          actualAmount: materList[inforIndex].planNum,
          actualNum: 0,
          barCodeDTOList: [],
          skuId: item.skuId || 0,
          materialRemark: item.materialRemark,
          materialType: item.materialFields ? item.materialFields.typeName : item.materialType,
          type: item.materialFields ? item.materialFields.type : item.type,
          supplierCode: this.supplierCode,
          supplierName: this.supplierInfo.name,
          // warehouseUserNickName: 
          stockMaterialDetaiList: (item.stockMaterialDetaiList || []).map(citem=>{
              return{
                barCode: citem.barCode,
                barCodeId: citem.barCodeId,
                count: citem.count,
                customerCode:null,
                customerName: null,
                inventoryDetailld: "",
                materialQuality:"1",
                planNum: citem.realNum,
                purchaseBatchNumber : null,
                realNum: citem.realNum,
                stockMaterialDetailld: "",
                stockMaterialId: item.id,
                supplierCode: this.supplierCode,
                supplierName: this.supplierInfo.name
              }
          }),
          id: null,
          materialEntity: {
            ...item.materialEntity,
            id: null,
          },
          warehouseCode: formData.warehouseCode,
          warehouseName: formData.warehouseName,
          warehouseUserName: formData.warehouseUserName,
        }
      })
      const params = {
        ...formData,
        planTime: (new Date(formData.planTime)).getTime(),
        stockTypeName: '采购入库',
        stockTypeCode: "purchase",
        relateOrders: purchaseCode,
        materialDetails: materialDetails,
        supplierCode: this.supplierCode,
        supplierName: this.supplierInfo.name
      }
      const res = await batchAddBarCode(barCodeLsit)
      console.log(res)
      if(res.data.code !== 200) {
        return Toast(res.data.message || '添加批次失败')
      }
      const result = await pdaAddPc(params)
      // 修改采购入库单的状态
      this.btnLoading = false
      const { code, data, message } = result.data || {}
      if (+code === 200) {
        Toast.success('新增成功')
        // 批量修改批次生产日期
        const setStock = await updateStockInventory(stockParams)
        sessionStorage.removeItem('currentFormData')
        this.$router.push("/allocation");
      } else {
        Toast(message)
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import "../../assets/css/common.scss";

.main-content {
  // height: auto;
  // min-height: calc(100vh - 200px);
  // margin-top: 135px;
  // background-image: linear-gradient(180deg, #548af1 0%, #84afff 72%, #ffffff 100%);
  // background-size:  100% 100px;
  // background-repeat: no-repeat;
  // position: relative;
  // z-index: 1;
}

.work-order-list {
  position: relative;
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f6f6f6;

  ::v-deep .van-tabs__nav {
    background: #f5f8f9;
  }

  .work-order-list-top {
    position: fixed;
    width: 100%;
    left: 0;
    top: 0;
    z-index: 2;
  }

  .search-box {
    // height: 46px;
    position: relative;

    .inner {
      font-size: 16px;
      color: #fff;
      padding: 8px 12px;
      background-color: #ffffff;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .van-search {
      flex: 1;
      padding: 0px 15px 0 3px;
      // height: 32px;
      border-radius: 4px;
      border: 1px #dedede solid;
    }

    .van-search__content {
      background-color: #ffffff;
      height: 32px;

      .van-cell {
        height: 30px;
        display: flex;
        align-items: center;
      }
    }

    .btn-wrap {
      width: 62px;
      height: 32px;
      background: #548af1;
      border-radius: 4px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-left: 7px;
      font-size: 14px;
      color: #fff;
    }

    .scan-box {
      display: flex;
      align-items: center;

      img {
        width: 20px;
      }
    }
  }

  .van-pull-refresh {
    height: calc(100% - 75px);
    overflow: scroll;

    /deep/ .van-pull-refresh__track {
      // overflow: scroll;
    }

    .van-list {
      height: 100%;
      // overflow: scroll;
    }

    .no-data {
      height: 100%;
      font-size: 14px;
      display: flex;
      justify-content: center;
      color: #c7c6c6;
      padding-top: 30px;
    }
  }

  .detail-box {
    width: 100%;
    display: flex;
    justify-content: center;
    background: linear-gradient(180deg, #548af1 0%, #84afff 72%, #ffffff 100%);
    height: 150px;
    margin-bottom: 38px;

    .detail {
      width: 94%;
      height: 147px;
      padding: 17px 7px 10px 7px;
      background: #ffffff;
      box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.16);
      border-radius: 8px;
      margin-bottom: 12px;
      z-index: 1;

      .d-1 {
        display: flex;
        justify-content: space-between;
        padding-bottom: 8px;
        margin-bottom: 9px;
        border-bottom: 1px solid #f3f3f3;

        .d-1-l {
          display: flex;

          img {
            width: 18.27px;
            height: 20px;
          }

          .idbox {
            font-size: 16px;
            font-family: Source Han Sans CN;
            font-weight: bold;
            color: #333333;
            margin-left: 8px;
          }
        }
      }

      .d-row {
        margin-bottom: 8px;
        font-size: 14px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        display: flex;
      }

      .d-l {
        color: #666666;
        margin-right: 8px;
      }

      .d-r {
        color: #333333;
      }

      .status {
        width: 39px;
        height: 20px;
        background: #ffffff;
        border: 1px solid #666666;
        border-radius: 2px;
        font-size: 12px;
        font-family: Source Han Sans CN;
        font-weight: 400;
        text-align: center;
        margin-right: 8px;
        display: flex;
        justify-content: center;
        align-items: center;

        &.take-effect {
          color: #0db45b;
          border: 1px solid #0db45b;
        }

        &.complete {
          color: #548af1;
          border: 1px solid #548af1;
        }
      }
    }
  }

  .no-data {
    height: 100%;
    font-size: 14px;
    display: flex;
    justify-content: center;
    color: #c7c6c6;
    padding-top: 30px;
  }

  .btnbox {
    display: flex;
    justify-content: space-around;
    align-items: center;
    padding: 9px 40px;
    background: #ffffff;

    .l-img {
      width: 22.47px;
      height: 24.96px;
    }

    .btn {
      width: 331px;
      height: 46px;
      background: #548af1;
      box-shadow: 0px 4px 8px rgba(8, 9, 29, 0.1);
      border-radius: 44px;
      font-size: 16px;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #ffffff;
      margin: 0 12px 0 14px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .btn-no {
      width: 331px;
      height: 46px;
      background: #dbdbdb;
      box-shadow: 0px 4px 8px rgba(8, 9, 29, 0.1);
      border-radius: 44px;
      font-size: 16px;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #ffffff;
      margin: 0 12px 0 14px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .r-img {
      width: 55px;
      height: 55px;
    }
  }

  .tabbar {
    width: 100%;
    padding: 10px 15px;
    background: #ffffff;
    position: fixed;
    left: 0;
    bottom: 0;
    // bottom: constant(safe-area-inset-bottom); /* iOS */
    // bottom: env(safe-area-inset-bottom); /* Android */
    display: flex;
    justify-content: space-around;
  }

  .action {
    // height: 64px;
    z-index: 99;
    background: #ffffff;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 9px 22px 9px 15px;
    display: flex;
    justify-content: space-between;
    min-height: 46px;

    .more {
      display: flex;
      align-items: center;
      position: relative;

      span {
        font-size: 14px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        color: #666666;
        margin-left: 10px;
      }

      .popover {
        position: absolute;
        bottom: 48px;
        left: -10px;
        width: 105px;
        height: 76px;

        background: #ffffff;
        box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
        opacity: 1;
        font-size: 17px;
        font-family: Source Han Sans CN, Source Han Sans CN;
        font-weight: 400;
        color: #548af1;
        text-align: center;
        line-height: 35px;
        display: flex;
        flex-direction: column;

        .el-button {
          flex: 1;
          margin: 0;
          border-bottom: 1px solid #f2f2f2;
        }

        // section {
        //   height: 35px;
        // }
        // section:nth-of-type(1) {
        //   border: 1px solid #f2f2f2;
        // }
      }
    }

    .btn {
      width: 264px;
      height: 46px;
      // background: #548af1;
      // box-shadow: 0px 4px 8px 1px rgba(8, 9, 29, 0.1);
      // border-radius: 4px 4px 4px 4px;
      // line-height: 46px;
      // font-weight: 400;
      // color: #ffffff;
      // text-align: center;
    }
  }

  .list-content-headerTitle {
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #333333;
    margin-bottom: 12px;
  }

  .list-content-title {
    font-size: 16px;
    font-family: Source Han Sans CN-Regular, Source Han Sans CN;
    font-weight: 400;
    color: #333333;
    margin-bottom: 12px;
  }

  .list-content-bottom {
    margin-top: 15px;

    .imgBox {
      text-align: right;

      img {
        width: 20px;
        height: 20px;
        margin-left: 10px;
      }
    }
  }

  .van-col {
    margin-bottom: 10px !important;
  }

  .title {
    width: 74px;
    font-size: 15px;
    font-family: SourceHanSansCN-Regular-, SourceHanSansCN-Regular;
    font-weight: normal;
    color: #666666;
  }

  .textContent {
    display: flex;

    align-items: center;

    .title {}

    ::v-deep .van-field {
      width: 73px;
      padding: 0;
      height: 28px;
      line-height: 28px;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      padding: 0 15px;

      &.van-field--error {
        border: 1px solid #ee0a24;
      }
    }
  }
}

.picker-box {
  width: 100%;
  background-color: #548af1;
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.select-box {
  width: 94%;
  height: 42px;
  margin-top: 5px;
  background-color: #ffffff;
  border-radius: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 10px;

  .select-label {
    color: #7e7e7e;
  }

  .select-box-item {
    flex: 1;
    word-break: break-all;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
  }
}

.scan-img {
  position: fixed;
  bottom: 13.5vh;
  right: 0;
  // transform: translateX(-50%);
  width: 82px;
  height: 82px;
  z-index: 2;
}

.scan-bg {
  flex: 0 1 40px;
  width: 40px;
  height: 40px;
  border-radius: 100%;
  background-color: #dbdbdb;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  box-shadow: 0 4px 8px #e6e6e6;

  img {
    width: 20px;
    height: 20px;
  }
}

.model-content {
  padding: 25px 10px 20px 26px;

  .name {
    font-size: 14px;
    color: #666666;
  }

  .value {
    font-size: 16px;
    color: #548af1;
    margin-top: 10px;
  }
}

.num {
  display: flex;
  min-width: 64px;
  padding: 6px;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  .num-l {
    font-size: 10px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    color: #333333;
  }

  .num-r {
    font-size: 12px;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    color: #f29a21;
  }

  &:nth-child(1) {
    background: rgba(255, 242, 223, 0.52);
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #fbb240;
    margin-right: 4px;

    .num-l {
      color: #f29a21;
    }
  }

  &:nth-child(2) {
    background: #e7ffe6;
    border-radius: 2px 2px 2px 2px;
    border: 1px solid #48ba47;

    .num-l {
      color: #48ba47;
    }

    .num-r {
      color: #48ba47;
    }
  }
}
</style>
